package cn.itlemon.security.main.handler;

import cn.hutool.json.JSONUtil;
import cn.itlemon.security.core.entity.common.ReturnMessage;
import cn.itlemon.security.core.entity.common.ReturnState;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证成功后的处理器
 *
 * @author jiangpingping
 * @date 2019/9/18 21:54
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();
        ReturnMessage<Authentication> rm = new ReturnMessage<>(ReturnState.OK);
        rm.setData(authentication);
        rm.setMessage("欢迎登录Spring Security入门到实践学习系统");
        writer.write(JSONUtil.toJsonStr(rm));
    }

}
